package com.fxiao.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginFilter extends HttpFilter {

	private ServletContext servletContext;

	@Override
	public void init(FilterConfig config) throws ServletException {
		this.servletContext = config.getServletContext();
	}

	@Override
	public void doFilter(HttpServletRequest request,
			HttpServletResponse response, FilterChain chain)
			throws IOException, ServletException {

		// 设置请求编码
		request.setCharacterEncoding("utf-8");
		// 设置响应编码
		response.setCharacterEncoding("utf-8");

		// 获取配置需要登录的页面地址
		String url = servletContext.getInitParameter("validate_login");
		//获取共用的页面（不需要登录可以就访问的页面地址）
		String common_page = servletContext.getInitParameter("common_page");
		// 获取配置的登录页面
		String login = servletContext.getInitParameter("login");
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		// 获取当前的 session
		HttpSession session = req.getSession();
		// 获取当前用户访问的路径地址
		String path = req.getServletPath();
		if (path.indexOf("user") != -1) {
			// 判断当前访问的路径，是否在配置的需要登录的页面地址中。
			System.err.println("url=" + url);
			System.err.println("path=" + path);
			if (url.indexOf(path) != -1 && session.getAttribute("user") != null) {
				req.setAttribute("base", req.getContextPath());
				chain.doFilter(request, response);
			} else if (common_page.indexOf(path) != -1) {
				req.setAttribute("base", req.getContextPath());
				chain.doFilter(request, response);
			} else {
				System.out.println("被拦截了....");
				resp.sendRedirect(req.getContextPath() + login);
			}
		} else {
			chain.doFilter(request, response);
		}
	}

}
